package com.loiot.baqi.controller;

import java.util.*;

import com.loiot.baqi.pojo.*;
import com.loiot.baqi.dao.*;
import com.loiot.baqi.service.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiot.baqi.pojo.*;
import com.loiot.baqi.constant.Const;
import com.loiot.baqi.constant.URLConst;
import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.service.*;
import com.loiot.baqi.status.AccountType;
import com.loiot.baqi.status.AssignmentStatus;
import com.loiot.baqi.status.ImportStatus;
import com.loiot.baqi.status.JoinStatus;
import com.loiot.baqi.status.KickStatus;
import com.loiot.commons.message.util.JsonUtil;
import com.timeloit.pojo.Account;
import com.loiot.baqi.utils.UserSessionUtils;


/**
 * 商务谈判 处理器。
 * WeiAccountQqGroupBusiness
 * @author  wangzx 
 * @creation 2016-08-11
 */


@Controller
@RequestMapping(value = "/weiAccountQqGroupBusiness")
public class WeiAccountQqGroupBusinessController {
    
    public static final AjaxResponse NAME_EXIST= new AjaxResponse(-100, "商务谈判已存在");
    
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Resource
	private WeiAccountQqGroupBusinessService weiAccountQqGroupBusinessService;
	
	private WeiAccountQqGroupBusiness weiAccountQqGroupBusiness;
	
	private HashMap<String,Object> pmap = new HashMap<String,Object>();
	 
	@Resource
	TgQqGroupService tgQqGroupService;
	
	/**
     * 跳转  商务谈判列表页
     * 
     * @return 模板位置
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
    		@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
    	WeiAccountQqGroupBusiness p, ModelMap model,HttpServletRequest request)throws Exception {
    	HashMap<String,Object> paramMap=this.getParaMap(jsonParam, model);
    	paramMap.put("qtype", "like");
    	String accountId = request.getParameter("accountId");
    	if(!StringUtils.isBlank(accountId)){
    		paramMap.put("accountId", accountId);	
    		request.setAttribute("accountId", accountId);
    	}
    	//用户数据过滤
    	/*
    	if(UserSessionUtils.getAccountType()==AccountType.HR.getCode() || UserSessionUtils.getAccountType()==AccountType.JOB_HUNTER.getCode() ){
    		paramMap.put("inPerson", UserSessionUtils.getAccount().getAccountId());
    	}*/
        Pager<WeiAccountQqGroupBusiness> pager = weiAccountQqGroupBusinessService.queryWeiAccountQqGroupBusinessListPage(paramMap , pageIndex);
        model.put("pager", pager);
        model.put("jsonParam", jsonParam);
        return "/tgQqgroupCooperation/weiAccountQqGroup_list";
    }
    
    /**
	 * 跳转 “用户_QQ群”概览列表页
	 * 
	 * @return 模板位置
	 */
	@RequestMapping(value = "/overviewList")
	public String overviewList(
			@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
			WeiAccountQqGroupBusiness p, ModelMap model) throws Exception {
		HashMap<String, Object> paramMap = this.getParaMap(jsonParam, model);
		paramMap.put("qtype", "like");
		Pager<WeiAccountQqGroupBusiness> pager = weiAccountQqGroupBusinessService
				.queryWeiAccountQqGroupBusinessOverviewListPage(paramMap, pageIndex);
		model.put("pager", pager);
		model.put("jsonParam", jsonParam);
		return "/tgQqgroupCooperation/weiAccountQqGroupOverview_list";
	}
    
    /**
     * 获取查询条件
     * @param jsonParam
     * @param model
     * @return
     */
    public HashMap<String,Object> getParaMap(String jsonParam,ModelMap model){
    	HashMap<String,Object> newParamMap = newParamMap =  new HashMap<String,Object>();
    	 HashMap<String,Object> paramMap =JsonUtil.toObject(jsonParam, HashMap.class);
		Iterator iter = paramMap.entrySet().iterator();
		while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
    		Object key = entry.getKey();
    		Object val = entry.getValue();
    		if(key.toString().equals("name")){
    			newParamMap.put("nameT", val);
    		}else
    		if(String.valueOf(val).length()>0){
    			newParamMap.put(String.valueOf(key), val);
        		model.put(String.valueOf(key), val);
    		}
		}
		return newParamMap;
    }

    /**
     * 跳转到添加页面
     * 
     * @return
     */
    @RequestMapping(value = "/toAdd")
    public String toAddWeiAccountQqGroupBusiness(ModelMap model) {
        
        return "/qqGroupBusiness/qqGroupBusiness_add";
    }

   
    
    /**
	 * 批量添加 用户_QQ群
	 * 
	 * @param p
	 *            对象参数
     * @param weiAccountQqGroupService 
	 * @param 多个群id
	 *            ，以逗号分隔
	 * @return ajax响应
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object addWeiAccountQqGroup(WeiAccountQqGroupBusiness p,String groupIds,
			HttpSession session, HttpServletRequest request, Object weiAccountQqGroupService) {
		try {
			Account account = (Account) session
					.getAttribute(Const.SESSION_USER_KEY);
			// 验证唯一性
			pmap.clear();
			// 一个群只能分配给一个用户
			String[] ids = groupIds == null ? new String[0] : groupIds
					.split(",");
			pmap.put("ids", ids);
			pmap.put("isKick", KickStatus.NOT_KICK.getCode());
			/*int result = weiAccountQqGroupService.getWeiAccountQqGroupListCount(pmap);
			if (result > 0) {
				return GROUP_ASSIGNED;
			}*/
			
			for(int i=0;i<ids.length;i++){
			//p.setIds(ids);
			p.setInPerson(account.getAccountId());
			Date now = new Date();
			p.setInTime(now);
			p.setUpdateTime(p.getInTime());
			p.setGroupId(Long.parseLong((ids[i])));
			p.setStatusUpdateTime(now);

			weiAccountQqGroupBusinessService.addWeiAccountQqGroupBusiness(p);
			
			TgQqGroup n =new TgQqGroup();
			n.setId(Long.parseLong((ids[i])));
			n.setUpdateTime(now);
			n.setBusinessAssignmentStatus(AssignmentStatus.ASSIGNED.getCode());
			n.setQqGroupBusinessId(p.getAccountId());
			tgQqGroupService.updateTgQqGroup(n);
			
		}
			// 添加成功
						return AjaxResponse.OK;
		} catch (Exception e) {
			e.printStackTrace();
			// 失败
			return AjaxResponse.FAILED;
		}

	}

    /**
     * 跳转到编辑页面
     * 
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public String toEditWeiAccountQqGroupBusiness(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)throws Exception {
        //model.put("p", weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessById(id));
    	if(id==null){
    		return URLConst.ERROR_URL;
    	}
    	model.put("pid",  id);
        return "/qqGroupBusiness/qqGroupBusiness_add";
    }

    /**
     * 更新 商务谈判
     * 
     * @param p 对象参数
     * @return ajax响应
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Object editWeiAccountQqGroupBusiness(WeiAccountQqGroupBusiness p,HttpSession session,HttpServletRequest request) {
    	/*try {
        // 获得账号
        //Account account = (Account) session.getAttribute(Const.SESSION_USER_KEY);
    		//如果前端，没有改变编号，就不用验证
        	String onlyName=request.getParameter("onlyName");
        	if(!StringUtils.isBlank(onlyName) &&  !p.getName().equals(onlyName)){
	    	//验证唯一性
        	pmap.clear();
        	//pmap.put("name", p.getName());
	    	int result=weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessListCount(pmap);
	    	if(result>0){
		        return NAME_EXIST;
			}
    	}
        weiAccountQqGroupBusinessService.updateWeiAccountQqGroupBusiness(p);
    	} catch (Exception e) {
			  e.printStackTrace();
			  return AjaxResponse.FAILED;
		}*/
        return AjaxResponse.OK;
    }

    /**
     * 跳转到查看页面
     * 
     * @return
     */
    @RequestMapping(value = "/toView")
    public String toViewWeiAccountQqGroupBusiness(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)throws Exception {
    	if(id==null){
    		return URLConst.ERROR_URL;
    	}
    	//model.put("p", weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessById(id));
    	 model.put("pid",  id);
    	return "/qqGroupBusiness/qqGroupBusiness_add";
    }

    /**
     * 删除  商务谈判
     * 
     * @param id WeiAccountQqGroupBusinessID
     */
    @RequestMapping(value = "/delete")
    public String deleteWeiAccountQqGroupBusiness(@RequestParam(value = "id", required = true) java.lang.Long id,HttpServletRequest request)throws Exception {
    	weiAccountQqGroupBusinessService.deleteWeiAccountQqGroupBusiness(id);
        String s = request.getHeader("Referer");
        String redirectStr = s.substring(s.indexOf("/weiAccountQqGroupBusiness/"), s.length());
        return "redirect:"+redirectStr;
    }
    
    /**
     * ajax删除  商务谈判
     * 
     * @param id WeiAccountQqGroupBusinessID
     */
    @RequestMapping(value = "/ajaxDelete")
    @ResponseBody
    public Object ajaxDeleteWeiAccountQqGroupBusiness(@RequestParam(value = "id", required = true) java.lang.Long id) {
    	try {
    		WeiAccountQqGroupBusiness p = new WeiAccountQqGroupBusiness();
        	//p.setLisLeaderCooperationEnd(id);
			weiAccountQqGroupBusinessService.deleteWeiAccountQqGroupBusiness(p);
			return AjaxResponse.OK;
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  return AjaxResponse.FAILED;
		}
    }
    
    /**
     * ajax 根据id查询实体bean
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public Object ajaxGetById(@RequestParam(value = "id", required = true) java.lang.Long id)throws Exception {
    	WeiAccountQqGroupBusiness p=null;
     	//用户数据过滤
     	/*if(UserSessionUtils.getAccountType()==AccountType.HR.getCode() || UserSessionUtils.getAccountType()==AccountType.JOB_HUNTER.getCode() ){
     		  p = weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessById(id, UserSessionUtils.getAccount().getAccountId());
     	} else {
   		      p = weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessById(id);
     	}*/
     	if(p==null){
     		return AjaxResponse.NOEXITS;
     	}
    	return AjaxResponse.OK(p);
    }
    
    /**
     * 更新 （停用、启用状态）
     * 
     * @param id 
     */
    @RequestMapping(value = "/modifyDeleteStatus")
    public String modifyDeleteStatus(@RequestParam(value = "id", required = true) java.lang.Long id,
    		@RequestParam(value = "deleteStatus", required = true) java.lang.Integer isDelete,
    		HttpServletRequest request)throws Exception {
    	WeiAccountQqGroupBusiness p = new WeiAccountQqGroupBusiness();
    	//p.setLisLeaderCooperationEnd(id);
    	//p.setIsDelete(isDelete);
    	weiAccountQqGroupBusinessService.updateWeiAccountQqGroupBusiness(p);
        String s = request.getHeader("Referer");
        String redirectStr = s.substring(s.indexOf("/weiAccountQqGroupBusiness/"), s.length());
        return "redirect:"+redirectStr;
    }
    
    /**
     * 重置群--将群分配给其他用户
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/resetGroup")
    @ResponseBody
    public Object checkNameExits(@RequestParam(value = "name", required = true) java.lang.String name,
    		@RequestParam(value = "oldname",required = false) java.lang.String oldName,
    		@RequestParam(value = "flag", required = true) String flag
    		) throws Exception
    {
    	//验证唯一性
    	pmap.clear();
    	pmap.put("name", name);
    	if("edit".equals(flag) && oldName.equals(name)){
        	return AjaxResponse.OK(null);
    	} 
    	int result=weiAccountQqGroupBusinessService.getWeiAccountQqGroupBusinessListCount(pmap);
    	if(result>0){
	        return NAME_EXIST;
		}
    	return AjaxResponse.OK(null);
    }
    

}
